package com.hs.shirodemo01.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hs.shirodemo01.exception.ProjectException;
import com.hs.shirodemo01.pojo.TbRole;
import com.hs.shirodemo01.service.TbRoleService;
import com.hs.shirodemo01.utils.Constant;
import com.hs.shirodemo01.utils.Result;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 郭敖
 * @since 2023-08-18
 */
@RestController
@RequestMapping("/roles")
public class TbRoleController {

    @Autowired
    private TbRoleService service;

    @RequiresPermissions("role:select")
    @GetMapping("/selectRoles/{pageNum}/{pageSize}")
    public Result findRoles(@PathVariable Integer pageNum, @PathVariable Integer pageSize){
        Page<TbRole> page = service.findRoles(pageNum, pageSize);
        HashMap<String,Object> map = new HashMap<>();
        map.put("total",page.getTotal());
        map.put("totalPages",page.getPages());
        map.put("list",page.getRecords());
        return Result.success(map);
    }

    @RequiresPermissions("role:select")
    @GetMapping("/selectRole/{id}")
    public Result fidnRole(@PathVariable Integer id){
        TbRole role = service.getById(id);
        return Result.success(role);
    }

    @RequiresPermissions("role:add")
    @PostMapping("/insertRole")
    public Result insertRole(@RequestBody TbRole role){
        if(!service.save(role)){
            throw new ProjectException(Constant.CREATED_ERR.getMsg(),Constant.CREATED_ERR.getCode());
        }
        return Result.success();
    }

    @RequiresPermissions("role:update")
    @PutMapping("/updateRole")
    public Result updateRole(@RequestBody TbRole role){
        if(!service.updateById(role)){
            throw new ProjectException(Constant.UPDATE_ERR.getMsg(), Constant.UPDATE_ERR.getCode());
        }
        return Result.success();
    }

    @RequiresPermissions("role:delete")
    @DeleteMapping("/deleteRole/{id}")
    public Result deleteRole(@PathVariable Integer id){
        if(!service.removeById(id)) {
            throw new ProjectException(Constant.DELETED.getMsg(), Constant.DELETED.getCode());
        }
        return Result.success();
    }

    @RequiresPermissions("role:updatePermission")
    @PutMapping("/updateOrAddPermissions")
    public Result updateOrAddPermissions(@RequestBody TbRole role){
        service.updateRolePermission(role);
        return Result.success();
    }
}

